package com.it.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.constants.SystemConstants;
import com.it.domain.ResponseResult;
import com.it.domain.dto.AddArticleDto;
import com.it.domain.entity.Article;
import com.it.domain.entity.ArticleTag;
import com.it.domain.entity.Category;
import com.it.domain.entity.Tag;
import com.it.domain.vo.*;
import com.it.mapper.ArticleMapper;
import com.it.mapper.ArticleTagMapper;
import com.it.mapper.TagMapper;
import com.it.service.ArticleService;
import com.it.service.ArticleTagService;
import com.it.service.CategoryService;
import com.it.utils.BeanCopyUtils;
import com.it.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.it.constants.SystemConstants.ARTICLE_STATUS_NORMAL;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleTagService articleTagService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章 封装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page<>(1, 5);
        page(page, queryWrapper);
        List<Article> articles = page.getRecords();

        List<HotArticleVo> articleVos = new ArrayList<>();
        //拷贝
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }
        articleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(articleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //如果 有categoryId就要 查询时压迫和传入的相同
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        //状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);

        List<Article> articles = page.getRecords();
        //查询categoryName
        articles.stream()
                .map(article -> {
                    //获取分类id 查询分类信息，获取分类名称
                    //把分类名称设置给article
                    return article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
                })
                .collect(Collectors.toList());
        //articleId去查询articleName进行配置
//        for(Article article:articles){
//            Category category = categoryService.getById(article.getCategoryId());
//            article.setCategoryName(category.getName());
//        }

        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        for (ArticleListVo articleListVo : articleListVos) {
            List<ArticleTag> articleTags = articleTagMapper.selectList(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId, articleListVo.getId()));
            LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Tag::getId, articleTags.stream().map(ArticleTag::getTagId).collect(Collectors.toList()));
            List<Tag> tags = new ArrayList<>();
            if (!articleTags.isEmpty()) {
                tags = tagMapper.selectList(queryWrapper);
            }
            articleListVo.setTags(tags.stream().map(tag -> {
                return tag.getName();
            }).collect(Collectors.toList()));
        }
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        //转换成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        List<ArticleTag> articleTags = articleTagMapper.selectList(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId, articleDetailVo.getId()));
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Tag::getId, articleTags.stream().map(ArticleTag::getTagId).collect(Collectors.toList()));
        List<Tag> tags = new ArrayList<>();
        if (!articleTags.isEmpty()) {
            tags = tagMapper.selectList(queryWrapper);
        }
        articleDetailVo.setTags(tags);
        //封装响应放回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应的id浏览量
        redisCache.incrementCacheMapValue("article:viewCount", id.toString(), 1);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult listTimeLine() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getCreateTime);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        List<TimeLineVo> timeLineVos = BeanCopyUtils.copyBeanList(articles, TimeLineVo.class);
        return ResponseResult.okResult(timeLineVos);
    }

    @Override
    public ResponseResult listCategoryArticle(Integer type, Long typeId) {
        List<Article> articles;
        if (type == 1) {
            articles = articleMapper.selectList(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId, typeId));
        } else if (type == 2) {
            List<Long> articleIds = articleTagMapper.selectList(
                            new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getTagId, typeId))
                    .stream().map(ArticleTag::getArticleId).collect(Collectors.toList());
            if (!articleIds.isEmpty()) articles = articleMapper.selectBatchIds(articleIds);
            else articles = Arrays.asList();
        } else articles = Arrays.asList();
        if (Objects.isNull(articles) || articles.isEmpty()) return null;
        articles.stream()
                .map(article -> {
                    //获取分类id 查询分类信息，获取分类名称
                    //把分类名称设置给article
                    return article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
                })
                .collect(Collectors.toList());
        List<CategoryArticleVo> categoryArticleVos = BeanCopyUtils.copyBeanList(articles, CategoryArticleVo.class);
        for (CategoryArticleVo articleVo : categoryArticleVos) {
            LambdaQueryWrapper<ArticleTag> queryWrapperA = new LambdaQueryWrapper<>();
            queryWrapperA.eq(ArticleTag::getArticleId, articleVo.getId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(queryWrapperA);
            LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Tag::getId, articleTags.stream().map(ArticleTag::getTagId).collect(Collectors.toList()));
            List<Tag> tags = tagMapper.selectList(queryWrapper);
            List<TagVo> tagVos = BeanCopyUtils.copyBeanList(tags, TagVo.class);
            tagVos = tagVos.stream().map(tagVo -> {
                tagVo.setArticleCount(Long.valueOf(articleTagMapper.selectCount(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getTagId, tagVo.getId()))));
                return tagVo;
            }).collect(Collectors.toList());
            articleVo.setTags(tagVos);
        }
        return ResponseResult.okResult(categoryArticleVos);
    }


}
